using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.ComponentModel;
using System.Text.RegularExpressions;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Net;

using FunctionInterface;
using WcfServices.Contracts;
using System.ServiceModel;

namespace Functions.Net
{
	/// <summary>
	/// 连接专用网络.
	/// 共享私密信息，登陆手机空间
	/// </summary>
	public class LinkSpecialNet : Activity, IProcessCommand, IDisposable
	{
		public LinkSpecialNet ()
		{
		}
		
		public event OutputMessageEventHandler OutputMessage;
		public FunctionInterface.Context Context {get; set;}
		
		private string ip = "192.168.1.123";
		private string port = "8080";
		//private int writeCount = 256;
		private int readCount = 4 * 1024;
		
		public List<string> GetCommnads ()
		{
			List<string> cms = new List<string>();
			cms.Add("-link ip");
			return cms;
		}
		
		public void Process (string command)
		{
			BasicHttpBinding binding = new BasicHttpBinding();
			EndpointAddress address = new EndpointAddress("http://192.168.1.123:80/OperationService");

			using (ChannelFactory<IOperation> channelFactory = new ChannelFactory<IOperation>(binding))
			{
				channelFactory.Endpoint.Address = address;
				IOperation proxy = channelFactory.CreateChannel();

				using (proxy as IDisposable)
				{
					Output( proxy.GetWeather(string.Empty));
				}
			}

		}
		
		public bool Validate (string command)
		{
			return true;
		}

		protected void TcpProcess (string command)
		{
			// 处理link ip:port
						//if(Regex.IsMatch(command, @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$"))
						if(command == "link")
						{
			//				string[] strs = command.Split(' ');
			//				ip = strs[0];
			//				port = strs[1];
							Connect(ip, int.Parse(port));
							_socket.Close ();
							return;
						}
						
						if(string.IsNullOrEmpty(ip) || string.IsNullOrEmpty(port))
						{
							return;
						}
						
						try
						{
							// 处理其他命令
							Connect(ip, int.Parse(port));
						    SendMessage(command);
						    string str = ReadMessage();
							Output(str, MessageType.ListMessage);
						}
						catch(Exception ex)
						{ 
							Toast.MakeText(Context.MainActivity, ex.ToString(), ToastLength.Long).Show();
						} 
						finally
						{
							_socket.Close ();
						}
		}
		
		Socket _socket;
        NetworkStream _stream;
		
		public virtual void Connect(string ipnumber, int portnumber)
		{
			try
            {
                //create a new client socket ...
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress remoteIPAddress = IPAddress.Parse(ipnumber);
                IPEndPoint remoteEndPoint = new IPEndPoint(remoteIPAddress, portnumber);
                _socket.Connect(remoteEndPoint);
            }
            catch
            {
				throw new Exception("连接远程主机失败。");
            }
		}
		
		public void SendMessage(string msg)
		{
		    try
            {
				msg += "\r\n";
                _stream = new NetworkStream(_socket); 
				_stream.Write(Encoding.UTF8.GetBytes(msg), 0, msg.Length);
                _stream.Flush();
            }
            catch 
            {
               throw new Exception("发送消息失败。");
            }
			finally
			{
				_stream.Close ();
			}
		}
		
		public string ReadMessage()
		{
			string str = string.Empty;
			try
            {
                _stream = new NetworkStream(_socket); 
                //_stream.ReadTimeout = 20000;// 20秒
				//if(_stream.CanRead && _stream.DataAvailable)
				//{
				Output("请稍候....");
				byte[] bs = new byte[readCount];
				_stream.Read(bs, 0, readCount);
				str = System.Text.Encoding.UTF8.GetString(bs);
				//}
            }
            catch
            {
				throw new Exception("读取消息失败。");
			}
			finally
			{
				_stream.Close ();
			}
			
			return str;
		}

		protected void Output (string strMessage)
		{
			if(OutputMessage != null)
			{
				OutputMessage(this, new OutputMessageEventArgs(strMessage));
			}
		}
		
		protected void Output (string strMessage, MessageType messageType)
		{
			if(OutputMessage != null)
			{
				OutputMessage(this, new OutputMessageEventArgs(strMessage));
			}
		}
		
		public void DisConnect()
		{
			if(_socket != null && _socket.Connected)
			{
				_socket.Close();
				_stream.Close();
			}
		}
		
		public new void Dispose ()
		{
			DisConnect();
		}
	}
}
